<template>
  <div class="questions-page">
    <div class="main-content">
      <div class="container">
        <h2 class=hstyle>互动问答</h2>
        <!-- <dd><a href="/mycourses">我的课程</a></dd> -->
        <p class="subtitle">互动问答板块包含每位同学就课程问题的交流学习。</p>
        <!-- <div>
          <button class="publish-button" @click="$router.push('/questions/publish-topic')">发布话题</button>
        </div> -->
      </div>
      <nav class="secondary-nav">
        <router-link :to="{ name: 'Questions', params: { tab: 'latest' } }" class="nav-item"
          :class="{ 'active': activeTab === 'latest' }" @click="changeTab('latest')">
          最新回答</router-link>
        <router-link :to="{ name: 'Questions', params: { tab: 'popular' } }" class="nav-item"
          :class="{ 'active': activeTab === 'popular' }" @click="changeTab('popular')">
          热门话题</router-link>

        <div class="search-container">
          <input type="text" placeholder="搜索话题" class="search" v-model="searchQuery" @input="searchResources" />
          <img src="@/assets/icon-search.png" alt="Search Icon" class="search-icon" />
        </div>
      </nav>
      <div class="content">

        <div v-if="activeTab === 'latest'">
          <div class="question-item" v-if="loading">
        正在加载......
      </div>
          <div v-for="(question, index) in currentLatestQuestions" :key="index" class="question-item">
            <!-- 点击问题条目时导航到详细页面 -->
            <router-link :to="'/questions/question-detail/' + question.id">
              <h3 class="pfontw">话题：{{ question.title }}</h3>
              <p class="contents">回复：{{ question.contents }}</p>
              <div class="qutionsth">
                <div class="question-header">
                  <img :src="question.avatar" alt="avatar" class="avatar">
                  <div class="question-info">
                    <p>
                      <span>{{ question.author }}&ensp;</span>
                      <span class="role1">学生 {{ question.role }}</span>
                      <span>&emsp;发表&emsp;|</span>
                      <span>&emsp;回复时间&emsp;{{ formatDateTime(question.lastdate) }}</span>
                    </p>
                  </div>
                </div>

                <div class="question-stats">
                  <span class="spanjiange">话题回复数: {{ question.replies }} </span>
                </div>
              </div>
            </router-link>
          </div>
        </div>

        <div v-if="activeTab === 'popular'">
          <div v-for="(question, index) in currentPopularQuestions" :key="index" class="question-item">
            <!-- 点击问题条目时导航到详细页面 -->
            <router-link :to="'/questions/question-detail/' + question.id + '?tab=popular'"
              @click="saveFromInfo('popular')">
              <h3 class="pfontw">话题:{{ question.title }}</h3>
              <div class="qutionsth">
                <div class="question-header">
                  <img :src="question.avatar" alt="avatar" class="avatar">
                  <div class="question-info">
                    <p>
                      <span>{{ question.author }}&ensp;</span>
                      <span class="role1">老师 {{ question.role }}</span>
                      <span>&emsp;发表&emsp;|</span>
                      <span>&emsp;最后回复&emsp;{{ formatDateTime(question.lastdate) }}</span>
                    </p>
                  </div>
                </div>

                <div class="question-stats">
                  <span class="spanjiange">回复: {{ question.replies }} </span>
                </div>
              </div>
            </router-link>
          </div>
        </div>
      </div>

      <div class="pagination">
        <button class="page-button" :disabled="currentPage === 1" @click="goToPage(currentPage - 1)">上一页</button>
        <span v-for="pageNumber in totalPages" :key="pageNumber">
          <button class="page-number" :class="{ active: pageNumber === currentPage }" @click="goToPage(pageNumber)">
            {{ pageNumber }}
          </button>
        </span>
        <button class="page-button" :disabled="currentPage === totalPages"
          @click="goToPage(currentPage + 1)">下一页</button>
      </div>

    </div>
  </div>
</template>


<script>
import axios from 'axios';
export default {
  props: {
    id: {
      type: String,
      required: true
    }
  },
  data() {
    return {
      activeTab: 'latest', // 默认选中的标签页
      // loading: true, // 加载状态，这里简化为true表示加载中
      fromPath: '', // 保存来源路径
      fromTab: '', // 保存来源选项卡信息
      questions: {
        latest: [], // 最新回答数据
        popular: [], // 热门话题数据
      },
      perPage: 5, // 每页显示条目数
      currentPage: 1, // 当前页码
      latestPage: 1, // 最新回答当前页码
      popularPage: 1, // 热门话题当前页码
      latestTotalPages: 0, // 最新回答总页数
      popularTotalPages: 0, // 热门话题总页数
      searchQuery:'',
      loading: true,
      
      // semester_id: 'current'  // 默认或当前学期的 ID，根据实际情况修改
    };
  },
  computed: {
    currentQuestions() {
      return this.activeTab === 'latest' ? this.currentLatestQuestions : this.currentPopularQuestions;
    },
    currentLatestQuestions() {
      const startIndex = (this.latestPage - 1) * this.perPage;
      const endIndex = startIndex + this.perPage;
      return this.questions.latest.slice(startIndex, endIndex);
    },
    currentPopularQuestions() {
      const startIndex = (this.popularPage - 1) * this.perPage;
      const endIndex = startIndex + this.perPage;
      return this.questions.popular.slice(startIndex, endIndex);
    },
    totalPages() {
      return this.activeTab === 'latest' ? this.latestTotalPages : this.popularTotalPages;
    }
  },
  mounted() {
    // 在组件挂载后立即获取数据
    this.fetchLatestQuestions();
    this.fetchPopularQuestions();
  },
  methods: {
    changeTab(tab) {
      this.activeTab = tab;
      this.saveFromInfo(tab);
      if (tab === 'latest') {
        this.currentPage = this.latestPage; // 切换选项卡时设置当前页为最新回答当前页
      } else if (tab === 'popular') {
        this.currentPage = this.popularPage; // 切换选项卡时设置当前页为热门话题当前页
      }

      // 添加以下逻辑来重置页码为第1页
      if (tab === 'latest') {
        this.currentPage = this.latestPage = 1; // 重置最新问答页码为第1页
      } else if (tab === 'popular') {
        this.currentPage = this.popularPage = 1; // 重置热门话题页码为第1页
      }
    },
    // 获取最新回答数据
    fetchLatestQuestions() {
      axios.get('http://8.138.12.59:1999/post/new')
        .then(response => {
          this.questions.latest = response.data.data.map(topic => ({
            id: topic.post_id,
            title: topic.content,
            contents: topic.newCommentContent,
            author: topic.user_name,
            //role: topic.publisher_id,
            lastdate: topic.update_time,
            replies: topic.comment_count,
            avatar: topic.img_url
          }));
          this.latestTotalPages = Math.ceil(this.questions.latest.length / this.perPage); // 更新最新回答总页数
          this.latestPage = 1; // 重置最新回答当前页为1
          this.loading=false;
        })
        .catch(error => {
          console.error('Error fetching latest questions:', error);
        });
    },
    //获取热门话题数据
    fetchPopularQuestions() {
      axios.get('http://8.138.12.59:1999/post/hot')
        .then(response => {
          this.questions.popular = response.data.data.map(topic => ({
            id: topic.post_id,
            title: topic.content,
            author: topic.user_name,
            //role: topic.publisher_id,
            lastdate: topic.update_time,
            replies: topic.comment_count,
            avatar: topic.img_url
          }));
          this.popularTotalPages = Math.ceil(this.questions.popular.length / this.perPage); // 更新热门话题总页数
          this.popularPage = 1; // 重置热门话题当前页为1
          // this.loading=false;
        })
        .catch(error => {
          console.error('Error fetching popular questions:', error);
        });
    },
    formatDateTime(datetime) {
      if (!datetime) return '';
      const date = new Date(datetime);
      const year = date.getFullYear();
      const month = ('0' + (date.getMonth() + 1)).slice(-2);
      const day = ('0' + date.getDate()).slice(-2);
      const hours = ('0' + date.getHours()).slice(-2);
      const minutes = ('0' + date.getMinutes()).slice(-2);
      const seconds = ('0' + date.getSeconds()).slice(-2);
      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    },
    goToPage(pageNumber) {
      const totalPages = this.activeTab === 'latest' ? this.latestTotalPages : this.popularTotalPages;
      if (pageNumber >= 1 && pageNumber <= totalPages) {
        if (this.activeTab === 'latest') {
          this.latestPage = pageNumber;
          this.currentPage = pageNumber; // 更新当前页码为最新回答的当前页
        } else if (this.activeTab === 'popular') {
          this.popularPage = pageNumber;
          this.currentPage = pageNumber; // 更新当前页码为热门话题的当前页
        }
      }
    },
    saveFromInfo(tab) {
      this.fromPath = this.$route.path; // 保存当前路径作为来源路径
      this.fromTab = tab; // 保存当前选项卡信息
    },
    searchResources() {
    const searchQuery = this.searchQuery.toLowerCase().trim();

    if (this.activeTab === 'latest') {
      // 搜索最新回答
      this.questions.latest = this.questions.latest.filter(question => {
        return question.title.toLowerCase().includes(searchQuery) ||
               question.contents.toLowerCase().includes(searchQuery) ||
               question.author.toLowerCase().includes(searchQuery);
      });
      // 更新最新回答的页数
      this.latestTotalPages = Math.ceil(this.questions.latest.length / this.perPage);
      this.latestPage = 1; // 重置页码为第1页
    } else if (this.activeTab === 'popular') {
      // 搜索热门话题
      this.questions.popular = this.questions.popular.filter(question => {
        return question.title.toLowerCase().includes(searchQuery) ||
               question.author.toLowerCase().includes(searchQuery);
      });
      // 更新热门话题的页数
      this.popularTotalPages = Math.ceil(this.questions.popular.length / this.perPage);
      this.popularPage = 1; // 重置页码为第1页
    }
  }
  },
  watch: {
    searchQuery(newValue) {
      if (newValue === '') {
        // 重置到原始数据
        this.fetchLatestQuestions();
        this.fetchPopularQuestions();
      }
    }
  },
  created() {
    // 组件创建时，根据当前的路由参数（query.tab）或默认加载最新回答数据
    const tab = this.$route.query.tab || 'latest';
    this.changeTab(tab);
  }
};
</script>

<style scoped>
.questions-page {
  display: flex;
  background-color: rgba(250, 250, 250, 1);
  margin: 0 150px 0 150px ;
}

.main-content {
  flex: 3;
  padding: 20px;
  background-color: rgba(250, 250, 250, 1);
  border-radius: 8px;
margin: 0;
}

.container {
  display: flex;
  margin-bottom: 40px;
}


.hstyle {
  font-size: 24px;
  text-decoration: none;
}


.subtitle {
  font-size: 14px;
  color: #888;
  margin-left: 30px;
  padding-top: 15px;
}


.publish-button {
  padding: 10px 20px;
  background-color: #007bff;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  margin-top: 15px;
  margin-left: 40px;
}

.secondary-nav {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
  border-bottom: 1px solid #e0e0e0;
}

.nav-item {
  width: 70px;
  padding: 10px 15px;
  color: #000;
  text-decoration: none;
  font-weight: bold;
}

.nav-item.active {
  color: #007bff;
  border-bottom: 2px solid #007bff;
}

.loading {
  text-align: center;
  margin-top: 20px;
}

.search-container {
  display: flex;
  align-items: center;
  margin-left: auto;
  margin-right: 70px;
  padding: 1px 10px;
  border: 1px solid #2a82e4;
  border-radius: 25px;
  background-color: #fff;
  margin-bottom: 5px;
}

.search {
  border: none;
  outline: none;
  padding: 5px;
  border-radius: 25px;
  flex: 1;
  margin-right: 10px;
}

.search-icon {
  width: 30px;
  height: 30px;
  cursor: pointer;
}

.content {
  margin-top: 20px;
}

.question-item {
  padding: 20px 20px 5px 20px;
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  margin-bottom: 20px;
  border: 1px solid rgb(223, 222, 222);
  /* 设置3像素宽的黑色实线边框 */

}

.contents {
  text-align: left;
  color: #000;
}

a {
  font-size: initial;
  /* 初始值，取消显式设置的字体大小 */
  font-weight: initial;
  /* 初始值，取消显式设置的字体粗细 */
  letter-spacing: normal;
  /* 取消显式设置的字母间距 */
  line-height: normal;
  /* 取消显式设置的行高 */
  color:rgba(59, 150, 255, 1);
  /* 初始值，取消显式设置的颜色 */
  text-decoration: none;
}

.pfontw {
  text-align: left;
  margin-top: -2px;
  color: #007bff;
}

.qutionsth {
  display: flex;
  font-size: 12px;
  margin: 0;
}

.question-header {
  display: flex;
  align-items: center;
  width: 500px;
}

.avatar {
  width: 50px;
  height: 50px;
  border-radius: 50%;
  margin-right: 10px;
}


.question-info p {
  margin: 5px 0 0;
  color: #888;
}

.role1 {
  background-color: #007bff;
  color: white;
  padding: 2px 4px;
  border-radius: 4px;
  margin-left: 5px;
}

.question-stats {
  margin-top: 19px;
  color: #888;
  width: 400px;
  /* margin-left: 150px; */
}

.spanjiange {
  margin-right: 50px;
}

.pagination {
  margin-top: 20px;
  text-align: center;
}

.page-button {
  background-color: #fff;
  border: 1px solid #007bff;
  color: #000;
  padding: 5px 10px;
  margin: 0 5px;
  cursor: pointer;
}

.page-button:hover {
  background-color: #007bff;
  color: #fff;
}

.page-button:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

.page-number {
  background-color: #fff;
  border: 1px solid #007bff;
  color: #000;
  padding: 5px 10px;
  margin: 0 5px;
  cursor: pointer;
}

.page-number.active {
  background-color: #007bff;
  color: #fff;
}
.dd{
  margin-top: 30px;
  margin-left: 30px;
}
.container h2{
  border: none;
  color:rgba(0, 0, 0, 1);
  font-size: 32px;
  font-weight: bold;
}
</style>
